package org.tang.springcloudvv.auth.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.tang.springcloudvv.auth.service.UserDetailsServiceImpl;
import org.tang.springcloudvv.util.TokenUtils;
import org.tang.springcloudvv.vo.UserData;

import javax.security.sasl.AuthenticationException;

/**
 * <p><em>Created on 2022/3/28 3:13 下午</em></p>
 *
 * @author fuzhongtang
 * @since 1.0.1
 */
@RestController
public class UserLoginController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @GetMapping("/token/login")
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            @RequestParam String username,
            @RequestParam String password) throws AuthenticationException {
        return ResponseEntity.ok(generateToken(username, password));
    }

    /**
     * 登陆与授权.
     * 返回token
     *
     * @param username .
     * @param password .
     * @return
     */
    private String generateToken(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        // Perform the security
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Reload password post-security so we can generate token
        final UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(username);

        UserData userData = new UserData();
        userData.setId(1);
        userData.setRole(1);
        userData.setName(userDetails.getUsername());
        String token = TokenUtils.buildToken(userData);
        return token;
    }
}
